<template>
  <div class="fm-uplaod-container"
       :id="uploadId"
  >

    <div class=""
         :class="{'is-disabled': disabled}"
         @click.self="handleAdd"
    >
      <i class="el-icon-upload" @click.self="handleAdd" style="      font-size: 40px;
    color: rgb(192, 196, 204);
    margin-left: 25px;
    margin-top: -10px;
    line-height: 50px;"></i>
      <input :accept="supportedTypeStr" v-if="multiple" multiple ref="uploadInput" @change="handleChange" type="file"
             :style="{width: 0, height: 0}" name="file" class="el-upload__input upload-input">
      <input :accept="supportedTypeStr" v-else ref="uploadInput" @change="handleChange" type="file"
             :style="{width:0, height: 0}" name="file" class="el-upload__input upload-input">
    </div>
    <ul class="el-upload-list el-upload-list--text" v-model="fileList"  v-if="fileList">


      <li class="el-upload-list__item is-success" v-for="(item,index) in fileList" :key="item.key">
        <span>
           <a class="el-upload-list__item-name" :href="item.url" target="_blank">{{item.name}}
             <i class="el-icon-document"></i>
              </a>
            <i class="el-icon-close"  @click="deleteImg(index,fileList)"></i>

        </span>



      </li>
    </ul>
  </div>


</template>

<script>
  import Viewer from 'viewerjs'
  import Draggable from 'vuedraggable'
  import * as qiniu from 'qiniu-js'
  import axios from 'axios'

  require('viewerjs/dist/viewer.css')

  export default {
    components: {
      Draggable
    },
    props: {
      value: {
        type: Array,
        default: () => []
      },
      width: {
        type: Number,
        default: 100
      },
      height: {
        type: Number,
        default: 100
      },
      token: {
        type: String,
        default: ''
      },
      domain: {
        type: String,
        default: ''
      },
      multiple: {
        type: Boolean,
        default: false
      },
      length: {
        type: Number,
        default: 9
      },
      isQiniu: {
        type: Boolean,
        default: false
      },
      isDelete: {
        type: Boolean,
        default: false
      },
      min: {
        type: Number,
        default: 0
      },
      meitu: {
        type: Boolean,
        default: false
      },
      editable: {
        type: Boolean,
        default: false
      },
      action: {
        type: String,
        default: ''
      },
      supportedTypeStr: {
        type: String,
        default: ''
      },
      disabled: {
        type: Boolean,
        default: false
      }
    },

    data() {
      return {
        fileList: this.getFileList() ,
        viewer: null,
        uploadId: 'upload_' + new Date().getTime(),
        editIndex: -1,
        meituIndex: -1,
      }
    },
    created() {
    },
    computed: {
      miniWidth() {
        if (this.width > this.height) {
          return this.height
        } else {
          return this.width
        }
      }
    },
    mounted() {
      if (this.fileList) {
        this.$emit('input', this.fileList)
      }
    },
    methods: {
      getFileList(){
        try {
          return    this.value instanceof Array ?
            this.value.map(item => {
              return {
                key: item.key ? item.key : (new Date().getTime()) + '_' + Math.ceil(Math.random() * 99999),
                url: item.url,
                name: item.name,
                percent: item.percent ? item.percent : 100,
                status: item.status ? item.status : 'success'
              }
            }) : []
        }catch (e) {

        }

      },
      deleteImg(index,list){
        this.fileList.splice(index, 1);
      },
      handleChange() {
        if (this.fileList) {
          if (this.fileList.length > this.length) {
            this.$message({
              "duration": '800',
              message: '上传文件数超过了最大限制',
              type: 'warning'
            });
            return
          }
          const files = this.$refs.uploadInput.files
          if (files.length > this.length) {
            this.$message({
              "duration": '800',
              message: '上传文件数超过了最大限制',
              type: 'warning'
            });
            return
          }
          for (let i = 0; i < files.length; i++) {
            const file = files[i]

            const reader = new FileReader()
            const key = (new Date().getTime()) + '_' + Math.ceil(Math.random() * 99999)
            reader.readAsDataURL(file)
            reader.onload = () => {
              if (this.editIndex >= 0) {
                this.$set(this.fileList, this.editIndex, {
                  key,
                  url: reader.result,
                  name: file.name,
                  percent: 0,
                  status: 'uploading'
                })

                this.editIndex = -1
              } else {
                this.fileList.push({
                  key,
                  url: reader.result,
                  name: file.name,
                  percent: 0,
                  status: 'uploading'
                })
              }

              this.$nextTick(() => {
                this.uplaodAction(reader.result, file, key)
              })
            }
          }
          this.$refs.uploadInput.value = []
        }

      },
      uplaodAction(res, file, key) {
        let changeIndex = this.fileList.findIndex(item => item.key === key)
        let formData = new FormData()
        formData.append('file', file)
        const url = this.action

        var options = {  // 设置axios的参数
          url: url,
          data: formData,
          name: file.name,
          method: 'post',
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }
        var configs = {
          headers:{'Content-Type':'multipart/form-data'}
        };
        // 文件上传
        axios.post(url,formData ,configs).then(res=>{
          let data = res.data
          if (data.code == 0) {
            this.$set(this.fileList, this.fileList.findIndex(item => item.key === key), {
              ...this.fileList[this.fileList.findIndex(item => item.key === key)],
              status: 'success',
              url: data.url,
            })
          } else {
            this.$message.error(data.message || '操作失败')
          }
        })
h
        // axios({
        //   method: "POST",
        //   url: url,
        //   data: formData,
        //   timeout:3000000
        // }).then((res) => {
        //   let data = res.data
        //   if (data.code == 0) {
        //     this.$set(this.fileList, this.fileList.findIndex(item => item.key === key), {
        //       ...this.fileList[this.fileList.findIndex(item => item.key === key)],
        //       status: 'success',
        //       url: data.url,
        //     })
        //   } else {
        //     this.$message.error(data.message || '操作失败')
        //   }
        // }).catch((e) => {
        //   alert(e)
        // })
      },
      handleRemove(key) {
        this.fileList.splice(this.fileList.findIndex(item => item.key === key), 1)
      },
      handleEdit(key) {

        this.editIndex = this.fileList.findIndex(item => item.key === key)

        this.$refs.uploadInput.click()
      },
      handleMeitu(key) {

        this.$emit('on-meitu', this.fileList.findIndex(item => item.key === key))
      },
      handleAdd() {
        if (!this.disabled) {
          this.editIndex = -1
          this.$refs.uploadInput.click()
        }
      },
      handlePreviewFile(key) {
        this.viewer && this.viewer.destroy()
        this.uploadId = 'upload_' + new Date().getTime()

        this.$nextTick(() => {
          this.viewer = new Viewer(document.getElementById(this.uploadId))
          this.viewer.view(this.fileList.findIndex(item => item.key === key))
        })
      }
    }
  }
</script>

<style lang="scss">
  .fm-uplaod-container {
    .is-disabled {
      position: relative;

      &::after {
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        // background: rgba(0,0,0,.1);
        content: '';
        display: block;
        cursor: not-allowed;
      }
    }

    .upload-file {
      margin: 0 10px 10px 0;
      display: inline-flex;
      justify-content: center;
      align-items: center;
      // background: #fff;
      overflow: hidden;
      background-color: #fff;
      border: 1px solid #c0ccda;
      border-radius: 6px;
      box-sizing: border-box;
      position: relative;
      vertical-align: top;

      &:hover {
        .uplaod-action {
          display: flex;
        }
      }

      .uplaod-action {
        position: absolute;
        // top: 0;
        // height: 30px;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0, 0, 0, 0.6);
        display: none;
        justify-content: center;
        align-items: center;

        i {
          color: #fff;
          cursor: pointer;
          margin: 0 5px;
        }
      }

      &.is-success {
        .item-status {
          position: absolute;
          right: -15px;
          top: -6px;
          width: 40px;
          height: 24px;
          background: #13ce66;
          text-align: center;
          transform: rotate(45deg);
          box-shadow: 0 0 1pc 1px rgba(0, 0, 0, .2);

          & > i {
            font-size: 12px;
            margin-top: 11px;
            color: #fff;
            transform: rotate(-45deg);
          }
        }
      }

      &.uploading {
        &:before {
          display: block;
          content: '';
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: rgba(0, 0, 0, 0.3);
        }
      }

      .upload-progress {
        position: absolute;

        .el-progress__text {
          color: #fff;
          font-size: 16px !important;
        }
      }

      img {
        max-width: 100%;
        max-height: 100%;
        vertical-align: middle;
      }
    }

    .el-upload--picture-card {
      position: relative;
      overflow: hidden;

      .el-icon-plus {
        position: absolute;
        top: 50%;
        left: 50%;
      }
    }

    .upload-input {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      display: block;
      opacity: 0;
      cursor: pointer;
    }

    .drag-img-list {
      display: inline;

      .ghost {
        position: relative;

        &::after {
          width: 100%;
          height: 100%;
          display: block;
          content: '';
          background: #fbfdff;
          position: absolute;
          top: 0;
          bottom: 0;
          left: 0;
          right: 0;
          border: 1px dashed #3bb3c2;
        }
      }

      & > div {
        cursor: move;
      }
    }
  }

  .viewer-container {
    z-index: 9999 !important;
  }
</style>
